<template>
    <div>
        <h4>发表评论</h4>
        <hr>
        <textarea placeholder="请输入要BB的内容，最多BB 120个字" maxlength="120" v-model="msg"></textarea>
        <mt-button type="primary" size="large" @click="postMsg">发表评论</mt-button>

        <!-- 评论列表区域 -->
        <div class="cmt-list">
            <div class="cmt-item" v-for="(item,i) in cmtlist" :key=i>
                <div class="cmt-item-title">第{{i+1}}楼&nbsp;用户：{{item.user_name}}&nbsp;发表时间:{{item.add_time|dataFormat}}</div>
                <div class="cmt-item-body">{{item.content}}</div>
            </div>

        </div>

        <mt-button type="danger" size="large" plain @click="loadMore">加载更多</mt-button>
    </div>
</template>

<script>
import { Toast } from 'mint-ui';

export default {
    data(){
        return {
            page:1,
            cmtlist: [],
            msg: "",
        };
    },
    created(){
        this.getConmmentByPage();
    },
    methods:{
        async getConmmentByPage(){
            //根据页数来获取评论的数据
            const {data}  = await this.$http.get(
                "/api/getcomments/"+ this.newid + "?pageindex=" + this.page)
            if(data.status ===0) return this.cmtlist = this.cmtlist.concat(data.message)
        },
        loadMore(){
            //点击按钮，加载更多的评论
            //当触发这个加载更多方法的时候，应该让 page页码+1之后，再调用getCommentByPage方法
            this.page++;
            this.getConmmentByPage();
        },
        async postMsg(){
            //点击发表评论
            //如果用户没有填写评论内容则组织其发表评论
            if(this.msg.trim().length<=0) return Toast({
                message:'请填写评论内容',
                duration: 1000,
            })
            //发表评论逻辑
            const {data} = await this.$http.post('/api/postcomment/'+this.newid,{content: this.msg.trim()})
            Toast({
                message: data.message,
                duration: 1000,
            })
            if(data.status === 0)
            //刷新评论表
            this.cmtlist.unshift({
                user_name: "匿名用户",
                add_time:new Date(),
                content:this.msg.trim(),
            });
            //评论数据清空
            this.msg = ""
        }
    },
    props:["newid"]
}
</script>

<style lang="scss" scoped>
textarea{
    font-size: 14px;
    margin: 0;
}
.cmt-list{
    margin-top: 4px;
    .cmt-item{
        line-height: 30px;
        .cmt-item-title{
            font-size: 14px;
            background-color: #ddd;
        }
        .cmt-item-body{
            font-size: 13px;
            text-indent: 2em;
        }
    }
}
</style>

